/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Service;

import Constants.Fishing_Command;
import Constants.PIConstants;
import Constants.Service;
import DataManager.DbManager;
import DataManager.MySQLCommonDataProvider;
import Message.Message;
import Message.SerializerHelper;
import Utility.CommonUtils;
import Utility.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author HaNH
 * Can phai co
 * 1.Constants.Fishing_Command; ( Su dung chung voi Fishing)
 * 2.FarmAnimals.java
 * 3.FarmLand.java
 * 4.MySQLCommonDataProvider.java co them 1 so Function
 * 5.Database them 3 Table: farm_land, farm_animals,farm_store
 * 6.Trong Table GlobalProperties Co them 2 value: money_exchange_rate=1000 ( Ti le quy doi giua Luong va Xu) va sell_animal_fee=10 ( Phi ban vat nuoi)
 */
public class FarmService {

    public static Logger log = LoggerFactory.getLogger(ParadiseService.class.getName());
    public static Logger logChat = LoggerFactory.getLogger("ChatLog");
    public static Logger logGame = LoggerFactory.getLogger("GameLog");

    public FarmService() {
        log.info("Farm initialized");

    }

    public void processCommand(IoSession session, int userID, String userName, Message clientMsg) {

        int actionCommand = clientMsg.getActionCommand();
        switch (actionCommand) {
            case Fishing_Command.REQUEST_JOIN_MAP:
                joinMap(session, clientMsg, userID);
                break;
            case Fishing_Command.REQUEST_FRIEND_LIST:
                showFriendList(session, clientMsg, userID);
                break;
            case Fishing_Command.REQUEST_VISIT_FARM:
                VisitFarm(session, clientMsg, userID);
                break;
            case Fishing_Command.REQUEST_ATM_INFO:
                viewATM(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_ATM_TRANSFER:
                transferATM(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_FARM_PLANT:
                plantTree(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_FIELD_ACTION:
                fieldAction(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_TREAT_ANIMAL:
                treatAnimals(session, userID, clientMsg);
                break;
            case Fishing_Command.RESPONSE_COLLECT:
                collectProduct(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_SELL_ANIMAL:
                sellAnimals(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_BUY_LAND:
                buyLand(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_VISIT_SHOP:
                visitShop(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_BUY_FARM_ITEM:
                buyFarmItems(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_FARM_IMAGE_SHOP:
                requestFarmShopImage(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_FARM_SELL_PRODUCT:
                sellFarmProduct(session, userID, clientMsg);
                break;
            case Fishing_Command.REQUEST_FARM_PRODUCT:
                viewFarmStore(session, userID, clientMsg);
                break;
        }
    }

    /**
     * 
     * @param session
     * @param clientMsg
     * @param userid 
     * 
     * Call when character get off the Bus. <br>
     * Server will check if the character has farm account. <br>
     * If the character doesn't have, Create a new one for him with 4 Lands, Farm money=0
     */
    public void joinMap(IoSession session, Message clientMsg, int userid) {

        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        commonDataProvider.createFarmUserIfNotExist(userid);
        Message msg = new Message(Fishing_Command.RESPONSE_JOIN_MAP, Service.FARM_SERVICE);
        session.write(msg);
    }

    /**
     * When Character Want to access Friend's Farm.  <br>
     * Character must enter the Friend's farm gate.<br>
     * Server will response His Friend List
     */
    private void showFriendList(IoSession session, Message clientMsg, int userid) {
        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        ArrayList listFriends = commonDataProvider.getFriendList(userid);


        Message msg = new Message(Fishing_Command.REQUEST_FRIEND_LIST, Service.FARM_SERVICE);
        SerializerHelper.writeInt(listFriends.size(), msg);

        for (int i = 0; i < listFriends.size(); i++) {
            UserObj user = (UserObj) listFriends.get(i);
            SerializerHelper.writeString(user.username, msg);
            SerializerHelper.writeInt(user.userid, msg);
            SerializerHelper.writeString(user.emotion_status, msg);

        }
        session.write(msg);

    }

    /**
     * When Character Enter the Farm gate.
     * farmOwner : 
     * If Visit character's farm, farmowner=0. 
     * If Visit friend's farm, farmowner=friend_id
     * 
     * Response the following Infomation:
     * 1.Farm Animals
     * 2.Farm Land
     * 3.Farm Seed (bought at Shop)
     * 4.Farm Vat Pham (bought at Shop)
     * 5.Farm Nong San ( Plant's product and animals's product)
     */
    private void VisitFarm(IoSession session, Message clientMsg, int userid) {

        int farmOwner = SerializerHelper.readInt(clientMsg);

        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        CharacterObj charObj = commonDataProvider.loadCharacterData(userid);

        Message msg;
        if ((int) charObj.idxHealthy < PIConstants.FARM_HEALTH_LIMIT) {
            msg = new Message(Fishing_Command.RESPONSE_VISIT_FARM_FAIL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(PIConstants.RESPONSE_VISIT_FARM_FAIL_HEALTH, msg);
        } else if ((int) charObj.idxHostility > PIConstants.FARM_HOSTILITY_LIMIT) {
            msg = new Message(Fishing_Command.RESPONSE_VISIT_FARM_FAIL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(PIConstants.RESPONSE_VISIT_FARM_FAIL_HOSTILITY, msg);
        } else {
            if (farmOwner != 0) {
                ParadiseService.updateUserIndex(userid, PIConstants.USER_INDEX_HOSTILITY, 
                        PIConstants.HOSTILITY_FARM_ADDED);
            } else {
                farmOwner = userid;
            }
            msg = new Message(Fishing_Command.RESPONSE_VISIT_FARM_SUCESS, Service.FARM_SERVICE);

            ArrayList listAnimals = commonDataProvider.getFarmAnimnals(farmOwner);
            SerializerHelper.writeInt(listAnimals.size(), msg); //  Field Size


            ArrayList listFields = commonDataProvider.getFieldList(farmOwner);
            SerializerHelper.writeInt(listFields.size(), msg); //  Field Size

            ArrayList listSeeds = null;
            ArrayList listItemsForTree = null;
            ArrayList listFoodForAnimals = null;
            ArrayList listDrugForAnimals = null;
            if (farmOwner == userid) {
                listSeeds = commonDataProvider.getFarmStore(userid, PIConstants.TYPE_FARM_PLANT);
                SerializerHelper.writeInt(listSeeds.size(), msg); //  Field Size
                listItemsForTree = commonDataProvider.getFarmStore(userid, PIConstants.TYPE_FARM_ITEM_FOR_TREE);
                SerializerHelper.writeInt(listItemsForTree.size(), msg); //  Field Size      
                listFoodForAnimals = commonDataProvider.getFarmStore(userid, PIConstants.TYPE_FARM_FOOD_FOR_ANIMAL);
                SerializerHelper.writeInt(listItemsForTree.size(), msg); //  Field Size      
                listDrugForAnimals = commonDataProvider.getFarmStore(userid, PIConstants.TYPE_FARM_DRUG_FOR_ANIMAL);
                SerializerHelper.writeInt(listDrugForAnimals.size(), msg); //  Field Size  
            } else {
                SerializerHelper.writeInt(0, msg); //  Field Size
                SerializerHelper.writeInt(0, msg); //  Field Size
                SerializerHelper.writeInt(0, msg); //  Field Size
                SerializerHelper.writeInt(0, msg); //  Field Size
            }

            int i;
            for (i = 0; i < listAnimals.size(); i++) {
                FarmAnimals animal = (FarmAnimals) listAnimals.get(i);
                SerializerHelper.writeInt(animal.itemid, msg); //  Field Size
                SerializerHelper.writeInt(animal.category, msg);
                SerializerHelper.writeInt(animal.id, msg); //  Field Size
                SerializerHelper.writeInt(animal.disease, msg); //  Field Size
                SerializerHelper.writeInt(animal.timegrow, msg); //  Field Size
                SerializerHelper.writeInt(animal.timegrowleft, msg); //  Field Size
                SerializerHelper.writeInt(animal.produce, msg); //  Field Size               
            }

            for (i = 0; i < listFields.size(); i++) {
                FarmLand land = (FarmLand) listFields.get(i);
                SerializerHelper.writeInt(land.landId, msg); //  Field Size
                SerializerHelper.writeInt(land.itemId, msg); //  Field Size
                SerializerHelper.writeInt(land.disease, msg); //  Field Size
                SerializerHelper.writeInt(land.duration, msg); //  Field Size
                SerializerHelper.writeInt(land.durationleft, msg); //  Field Size

            }

            if (listSeeds != null) {

                for (i = 0; i < listSeeds.size(); i++) {
                    FarmStuff stuff = (FarmStuff) listSeeds.get(i);
                    SerializerHelper.writeInt(stuff.id, msg);
                    SerializerHelper.writeString(stuff.name, msg);
                    SerializerHelper.writeInt(stuff.amount, msg);
                }

                for (i = 0; i < listItemsForTree.size(); i++) {
                    FarmStuff stuff = (FarmStuff) listItemsForTree.get(i);
                    SerializerHelper.writeInt(stuff.id, msg);
                    SerializerHelper.writeString(stuff.name, msg);
                    SerializerHelper.writeInt(stuff.category, msg);
                    SerializerHelper.writeInt(stuff.amount, msg);
                }

                for (i = 0; i < listFoodForAnimals.size(); i++) {
                    FarmStuff stuff = (FarmStuff) listFoodForAnimals.get(i);
                    SerializerHelper.writeInt(stuff.id, msg);
                    SerializerHelper.writeString(stuff.name, msg);
                    SerializerHelper.writeInt(stuff.category, msg);
                    SerializerHelper.writeInt(stuff.amount, msg);
                }

                for (i = 0; i < listDrugForAnimals.size(); i++) {
                    FarmStuff stuff = (FarmStuff) listDrugForAnimals.get(i);
                    SerializerHelper.writeInt(stuff.id, msg);
                    SerializerHelper.writeString(stuff.name, msg);
                    SerializerHelper.writeInt(stuff.category, msg);
                    SerializerHelper.writeInt(stuff.amount, msg);
                }
            }
        }
        session.write(msg);
    }

    /**
     * View ATM when Character reach ATM 
     * Responds:
     * 1.FarmMoney
     * 2.Main Money
     * 3.Vip Money
     */
    private void viewATM(IoSession session, int userID, Message clientMsg) {

        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        int farmMoney = commonDataProvider.getFarmMoney(userID);
        int mainMoney = commonDataProvider.retrieveAccountBalance(userID);
        int vipMoney = 123;

        /*
         * TODO: Vip money
         */

        Message msg = new Message(Fishing_Command.RESPONSE_ATM_INFO, Service.FARM_SERVICE);
        SerializerHelper.writeInt(farmMoney, msg);
        SerializerHelper.writeInt(vipMoney, msg);
        SerializerHelper.writeInt(mainMoney, msg);

        session.write(msg);

    }

    /**
     * Transfer ATM
     * 1.From Main to Farm
     * 2.From Farm to Main
     */
    private void transferATM(IoSession session, int userID, Message clientMsg) {

        boolean isfromMain = SerializerHelper.readBoolean(clientMsg);
        int amount = SerializerHelper.readInt(clientMsg);
        Message msg = null;

        if (amount > PIConstants.ATM_TRANSFER_LIMIT_MAX) {
            msg = new Message(Fishing_Command.RESPONSE_ATM_TRANSFER_FAIL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(PIConstants.ATM_TRANSFER_LIMIT_MAX, msg);
        } else if (amount < PIConstants.ATM_TRANSFER_LIMIT_MIN) {
            msg = new Message(Fishing_Command.RESPONSE_ATM_TRANSFER_FAIL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(PIConstants.ATM_TRANSFER_LIMIT_MIN, msg);
        } else {
            MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
            int balance = 0;

            if (isfromMain) {
                balance = commonDataProvider.retrieveAccountBalance(userID);
            } else {
                balance = commonDataProvider.getFarmMoney(userID);
            }
            if (amount > balance) { // NOT ENOUGH
                msg = new Message(Fishing_Command.RESPONSE_ATM_TRANSFER_FAIL, Service.FARM_SERVICE);
                SerializerHelper.writeInt(PIConstants.ATM_TRANSFER_LIMIT_MIN, msg);
                SerializerHelper.writeInt(PIConstants.ATM_TRANSFER_NOT_ENOUGH_MONEY, msg);
            } else { // OK
                int amountReceive = amount * (100 - PIConstants.ATM_TRANSFER_FEE_PERCENT) / 100;
                commonDataProvider.transferFarmATM(userID, amount, amountReceive, isfromMain);
                msg = new Message(Fishing_Command.RESPONSE_ATM_TRANSFER_SUCCESS, Service.FARM_SERVICE);
            }
        }
        session.write(msg);
    }

    /**
     * 
     * When character plant tree
     * Server check if the land can Plant tree and amount Of Seed >0
     * If successful, Amount of Seed will be subtract from Farm Store 
     *  
     */
    private void plantTree(IoSession session, int userID, Message clientMsg) {
        int landId = SerializerHelper.readInt(clientMsg);
        int itemId = SerializerHelper.readInt(clientMsg);

        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();

        if (commonDataProvider.canPlantTree(userID, landId) && commonDataProvider.countItemFarmStoreByID(userID, itemId, PIConstants.TYPE_FARM_PLANT) > 0) {

            Message msg = new Message(Fishing_Command.RESPONSE_FARM_PLANT_SUCCESS, Service.FARM_SERVICE);
            commonDataProvider.plantTree(userID, landId, itemId);
            session.write(msg);

        }

    }

    /**
     * Action on Fields
     * 1.Harvest   ( Will response Amount of Product collected)
     * 2.fertilizing
     * 3.herbicide ( Diet co)
     * 4.killWorms
     * 5.doSoil
     * 6.watering 
     * 
     */
    private void fieldAction(IoSession session, int userID, Message clientMsg) {
        int landId = SerializerHelper.readInt(clientMsg);
        int actionCode = SerializerHelper.readInt(clientMsg);


        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();

        Message msg = new Message(Fishing_Command.RESPONSE_FIELD_ACTION, Service.FARM_SERVICE);
        SerializerHelper.writeInt(actionCode, msg);
        int result = -1;
        if (actionCode == PIConstants.REQUEST_FIELD_THU_HOACH) { // Thu hoach
            result = commonDataProvider.harvest(userID, landId);
        } else if (actionCode == PIConstants.REQUEST_FIELD_BON_PHAN) {
            result = commonDataProvider.fertilizing(userID, landId);
        } else if (actionCode == PIConstants.REQUEST_FIELD_DIET_CO) {
            commonDataProvider.herbicide(userID, landId);
        } else if (actionCode == PIConstants.REQUEST_FIELD_DIET_SAU) {
            commonDataProvider.killWorms(userID, landId);
        } else if (actionCode == PIConstants.REQUEST_FIELD_LAM_DAT) {
            commonDataProvider.doSoil(userID, landId);
        } else if (actionCode == PIConstants.REQUEST_FIELD_TUOI_NUOC) {
            commonDataProvider.watering(userID, landId);
        }
        SerializerHelper.writeInt(result, msg);
        session.write(msg);
    }

    private void treatAnimals(IoSession session, int userID, Message clientMsg) {
        int animalCategory = SerializerHelper.readInt(clientMsg);
        int animalorder = SerializerHelper.readInt(clientMsg);
        int actionid = SerializerHelper.readInt(clientMsg);

        int itemCategory = 0;
        int itemType = PIConstants.TYPE_FARM_DRUG_FOR_ANIMAL; // DEFAULT
        String updatefield = "";
        int nexthour = 0;
        if (actionid == PIConstants.FLAG_ACTION_FEED_ANIMAL) {
            itemType = PIConstants.TYPE_FARM_FOOD_FOR_ANIMAL;
            itemCategory = animalCategory;
            nexthour = 12 + CommonUtils.random(12);
            updatefield = "time_hungry";
        } else if (actionid == PIConstants.FLAG_ACTION_TONIC_ANIMAL) {
            itemCategory = PIConstants.CATEGORY_FARM_ANIMAL_TONIC;
            nexthour = 24 + CommonUtils.random(24); // IN HOUR
            updatefield = "time_tired";
        } else if (actionid == PIConstants.FLAG_ACTION_TREAT_ANIMAL_FLU) {
            itemCategory = PIConstants.CATEGORY_FARM_ANIMAL_FLU;
            nexthour = 24 + CommonUtils.random(24);
            updatefield = "time_have_flu";
        } else if (actionid == PIConstants.FLAG_ACTION_TREAT_ANIMAL_HEADACHE) {
            itemCategory = PIConstants.CATEGORY_FARM_ANIMAL_HEADACHE;
            nexthour = 24 + CommonUtils.random(24);
            updatefield = "time_headache";
        }

        if (itemCategory > 0 && itemType > 0) {
            MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
            commonDataProvider.treatAnimal(userID, animalorder, itemCategory, itemType, updatefield, nexthour);
            Message msg = new Message(Fishing_Command.RESPONSE_TREAT_ANIMAL, Service.FARM_SERVICE);
            session.write(msg);
        }
    }

    private void collectProduct(IoSession session, int userID, Message clientMsg) {
        int itemCategory = SerializerHelper.readInt(clientMsg);
        if (itemCategory == PIConstants.CATEGORY_FARM_IS_FOR_HEN || itemCategory == PIConstants.CATEGORY_FARM_IS_FOR_COW) {
            MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
            int sanluong = commonDataProvider.collectAnimalProduct(userID, itemCategory);
            Message msg = new Message(Fishing_Command.RESPONSE_COLLECT, Service.FARM_SERVICE);
            SerializerHelper.writeInt(sanluong, msg);
            session.write(msg);
        }
    }

    private void sellAnimals(IoSession session, int userID, Message clientMsg) {
        int itemCategory = SerializerHelper.readInt(clientMsg);
        int id = SerializerHelper.readInt(clientMsg);
        if (itemCategory != PIConstants.CATEGORY_FARM_IS_FOR_DOG) {
            MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
            int money = commonDataProvider.sellAnimals(userID, itemCategory, id);
            Message msg = new Message(Fishing_Command.RESPONSE_SELL_ANIMAL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(itemCategory, msg);
            SerializerHelper.writeInt(id, msg);
            SerializerHelper.writeInt(money, msg);
            session.write(msg);
        }
    }

    private void buyLand(IoSession session, int userID, Message clientMsg) {
        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        int price = commonDataProvider.getGlobalProperties(PIConstants.STRING_FARM_LAND_PRICE);
        
        int balance = commonDataProvider.getFarmMoney(userID);
        Message msg = null;
        if (balance < price) {
            msg = new Message(Fishing_Command.RESPONSE_BUY_LAND_FAIL, Service.FARM_SERVICE);
            SerializerHelper.writeInt(PIConstants.RESPONSE_BUY_LAND_FAIL_NOT_ENOUGH_MONEY, msg);
        } else {
            commonDataProvider.buyLand(userID, price);
            msg = new Message(Fishing_Command.RESPONSE_BUY_LAND_SUCCESS, Service.FARM_SERVICE);
            SerializerHelper.writeInt(balance - price, msg);
        }
        session.write(msg);
    }

    private void visitShop(IoSession session, int userID, Message clientMsg) {
        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        int farmmoney = commonDataProvider.retrieveAccountBalance(userID);


        ArrayList listPlant = commonDataProvider.getFarmItems(PIConstants.TYPE_FARM_PLANT);
        ArrayList listAnimal = commonDataProvider.getFarmItems(PIConstants.TYPE_FARM_ANIMAL);
        ArrayList listItemForTree = commonDataProvider.getFarmItems(PIConstants.TYPE_FARM_ITEM_FOR_TREE);
        ArrayList listFoodForAnimal = commonDataProvider.getFarmItems(PIConstants.TYPE_FARM_FOOD_FOR_ANIMAL);
        ArrayList listDrugForAnimal = commonDataProvider.getFarmItems(PIConstants.TYPE_FARM_DRUG_FOR_ANIMAL);
        ArrayList listFarmProduct = commonDataProvider.getFarmStore(userID, PIConstants.TYPE_FARM_PLANT_PRODUCT);
        ArrayList listAnimalProduct = commonDataProvider.getFarmStore(userID, PIConstants.TYPE_FARM_ANIMAL_PRODUCT);

        Message msg = new Message(Fishing_Command.RESPONSE_VISIT_SHOP, Service.FARM_SERVICE);
        SerializerHelper.writeInt(farmmoney, msg);
        SerializerHelper.writeInt(listItemForTree.size() + listFoodForAnimal.size() + listDrugForAnimal.size(), msg); // VAT PHAM
        SerializerHelper.writeInt(listPlant.size(), msg);
        SerializerHelper.writeInt(listAnimal.size(), msg);
        SerializerHelper.writeInt(listAnimalProduct.size() + listFarmProduct.size(), msg);


        FarmStuff stuff = null;
        int i = 0;
        // Vat Pham
        for (i = 0; i < listItemForTree.size(); i++) {
            stuff = (FarmStuff) listItemForTree.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.money, msg);
        }
        for (i = 0; i < listFoodForAnimal.size(); i++) {
            stuff = (FarmStuff) listFoodForAnimal.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.money, msg);
        }
        for (i = 0; i < listDrugForAnimal.size(); i++) {
            stuff = (FarmStuff) listDrugForAnimal.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.money, msg);
        }

        // Giong Cay Trong

        for (i = 0; i < listPlant.size(); i++) {
            stuff = (FarmStuff) listPlant.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.timegrow, msg);
            SerializerHelper.writeInt(stuff.money, msg);
            SerializerHelper.writeInt(stuff.income, msg);
            SerializerHelper.writeString(stuff.description, msg);
        }

        // Giong Vat Nuoi
        for (i = 0; i < listAnimal.size(); i++) {
            stuff = (FarmStuff) listAnimal.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.timegrow, msg);
            SerializerHelper.writeInt(stuff.money, msg);
            SerializerHelper.writeInt(stuff.vipmoney, msg);
            SerializerHelper.writeInt(stuff.income, msg);
            SerializerHelper.writeString(stuff.description, msg);
        }

        // Farm Product        
        for (i = 0; i < listFarmProduct.size(); i++) {
            stuff = (FarmStuff) listFarmProduct.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.amount, msg);
        }

        // Animal Product
        for (i = 0; i < listAnimalProduct.size(); i++) {
            stuff = (FarmStuff) listAnimalProduct.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.amount, msg);
        }

        session.write(msg);
    }

    private void buyFarmItems(IoSession session, int userID, Message clientMsg) {
        int itemId = SerializerHelper.readInt(clientMsg);
        int amount = SerializerHelper.readInt(clientMsg);

        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();

        int money = commonDataProvider.getFarmMoney(userID);
        int price = commonDataProvider.getFarmItemPrice(itemId);
        if(price<0){
            return;
        }
        Message msg = null;
        if (money >= price * amount) {
            commonDataProvider.buyFarmItems(userID, itemId, amount);
            msg = new Message(Fishing_Command.RESPONSE_BUY_FARM_ITEM_SUCCESS, Service.FARM_SERVICE);
        } else {
            msg = new Message(Fishing_Command.RESPONSE_BUY_FARM_ITEM_FAIL, Service.FARM_SERVICE);
        }
        session.write(msg);
    }

    private void sellFarmProduct(IoSession session, int userID, Message clientMsg) {
        int itemId = SerializerHelper.readInt(clientMsg);
        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        commonDataProvider.sellFarmProduct(userID, itemId);
        Message msg = new Message(Fishing_Command.RESPONSE_FARM_SELL_PRODUCT, Service.FARM_SERVICE);
        session.write(msg);
    }

    private void requestFarmShopImage(IoSession session, int userID, Message clientMsg) {
        try {
            int numOfimages = SerializerHelper.readInt(clientMsg);

            Message msg = new Message(Fishing_Command.RESPONSE_FARM_IMAGE_SHOP, Service.FARM_SERVICE);
            MySQLCommonDataProvider dataManager = DbManager.GetCommonDataManager();
            SerializerHelper.writeInt(numOfimages, msg);
            for (int i = 0; i < numOfimages; i++) {
                int itemId = SerializerHelper.readInt(clientMsg);
                InputStream stream = dataManager.getItemFarmImage(itemId);


                SerializerHelper.writeInt(itemId, msg);
                if (stream == null) {
                    SerializerHelper.writeInt(0, msg);
                } else {
                    int bufsize = stream.available();
                    byte[] buffer = IOUtils.readFully(stream, bufsize, true);
                    SerializerHelper.writeInt(bufsize, msg);
                    SerializerHelper.write(buffer, 0, bufsize, msg);
                }
            }
            session.write(msg);
        } catch (IOException ex) {
            log.error(ex.getClass().getName(), ex);
        }
    }

    private void viewFarmStore(IoSession session, int userID, Message clientMsg) {
        MySQLCommonDataProvider commonDataProvider = DbManager.GetCommonDataManager();
        ArrayList listFarmProduct = commonDataProvider.getFarmStore(userID, PIConstants.TYPE_FARM_PLANT_PRODUCT);
        ArrayList listAnimalProduct = commonDataProvider.getFarmStore(userID, PIConstants.TYPE_FARM_ANIMAL_PRODUCT);

        Message msg = new Message(Fishing_Command.RESPONSE_FARM_PRODUCT, Service.FARM_SERVICE);

        SerializerHelper.writeInt(listFarmProduct.size() + listAnimalProduct.size(), msg);

        for (int i = 0; i < listFarmProduct.size(); i++) {
            FarmStuff stuff = (FarmStuff) listFarmProduct.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.amount, msg);
        }
        for (int i = 0; i < listAnimalProduct.size(); i++) {
            FarmStuff stuff = (FarmStuff) listAnimalProduct.get(i);
            SerializerHelper.writeInt(stuff.id, msg);
            SerializerHelper.writeString(stuff.name, msg);
            SerializerHelper.writeInt(stuff.amount, msg);
        }

        session.write(msg);
    }
}
